//
//  OAInBoxViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/28.
//  Copyright © 2016年 czd. All rights reserved.
//

#import "OAInBoxViewController.h"
#import "UnDoneModel.h"
#import "OAUnDoneListCell.h"
#import "OAInBoxDetailViewController.h"

@interface OAInBoxViewController ()
@property(nonatomic,assign)BOOL isSearching;

@end

@implementation OAInBoxViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
     UIBarButtonItem * rightIem = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction)];
//        self.navigationItem.rightBarButtonItem = rightIem;
    
    self.title = _string;
[self.tableView addHeaderWithCallback:^{
        self.currentPage = 1;
        [self loadData]; //加载网络数据
    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
            [self loadMore];
            
        }else{
            
            [self.tableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
            
        }
        
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshData" object:nil];
}

-(void)searchAction{
    
    [UIAlertView showWithTitle:@"搜索" message:nil style:UIAlertViewStylePlainTextInput cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        [self.view endEditing:YES];
        
        if (buttonIndex == 1) {
            UITextField * textField = [alertView textFieldAtIndex:0];
            if (textField.text.length !=0) {
                
                [self.dataArray removeAllObjects];
                self.isSearching = YES;
                self.currentPage = 1;
                [self loadSearchData:textField.text];
            }
            
        }
        
    }];
    
}
-(void)loadSearchData:(NSString*)text{
    NSString * method = nil;
    self.searchText = text;
            method = @"FilesDispatchSearch";
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"Condition":text},@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    __weak typeof(self) weakSelf = self;
   [HttpTools postWithURL:exchSearch arrays:array method:method success:^(id JSON) {
        if (self.currentPage == 1) {
            [self.dataArray removeAllObjects];
        }
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];

        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
    
    
}




-(NSMutableArray*)dataArray{
    if (_dataArray == nil) {
        _dataArray =   [NSMutableArray array];
    }
    return _dataArray;
}
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
        if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
        self.dataArray =  [self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]];
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
            [self.view makeToast:@"暂时还没数据哦"];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
        
    }];
    
}
-(void)refreshData{
    self.currentPage = 1;
    [self loadData];

}
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
        self.currentPage++;
                [self.tableView reloadData];

        [self.tableView footerEndRefreshing];
    } failure:^(NSError *error) {
        [self.tableView footerEndRefreshing];
    }];
    
}
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"发送时间"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
             GDataXMLElement * isReadElement = [[data elementsForName:@"是否已读"] objectAtIndex:0];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.fileId = [fileIdElement stringValue];
            model.isRead = [isReadElement stringValue];
            model.iconType = @"InBox"; //发送箱
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue] ;
        
    }
    self.title = [NSString stringWithFormat:@"%@(%d)",_string, self.totalCounts];
    return array;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UnDoneModel * model = self.dataArray[indexPath.row];
    CGFloat height = 0;
    CGFloat  titlesize  = [OAToolBox sizebyText:model.title font:14 minsWidth:80];
    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
    CGFloat dessize = [OAToolBox sizebyText:desstring font:13 minsWidth:60];;
    height = titlesize + dessize + 20;
    return  height;
//return ( KScreenHeight-64)/10;
}




#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OAUnDoneListCell * cell = [OAUnDoneListCell cellWithTableView:tableView];
    UnDoneModel * model = self.dataArray[indexPath.row];
    
    
    if ([_type isEqualToString:@"1"]){
     if (![model.isRead isEqualToString:@"1"]) {
         
 cell.contentView.backgroundColor = [UIColor colorWithRed:231/255.0 green:231/255.0 blue:231/255.0 alpha:1];
        }
        else{
      cell.contentView.backgroundColor = [UIColor whiteColor];
        }
}
    cell.model = model;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     UnDoneModel * model = self.dataArray[indexPath.row];
    OAInBoxDetailViewController * inBoxDetail = (OAInBoxDetailViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"InBoxDetailID"];
    inBoxDetail.fileId = model.fileId;
    [self.navigationController pushViewController:inBoxDetail animated:YES];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
